package com.sl.hx.shop;

import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Build;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.text.TextUtils;
import android.util.Base64;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.target.SimpleTarget;
import com.bumptech.glide.request.transition.Transition;
import com.sl.hx.shop.base.BaseActivity;
import com.sl.hx.shop.base.BasePresenter;
import com.sl.hx.shop.bean.SplashBean;
import com.sl.hx.shop.bean.TokenBean;
import com.sl.hx.shop.constant.AppConfig;
import com.sl.hx.shop.constant.SPUKey;
import com.sl.hx.shop.http.ApiFactory;
import com.sl.hx.shop.http.HttpUtil;
import com.sl.hx.shop.http.ProgressSubscribe;
import com.sl.hx.shop.utils.FileUtil;
import com.sl.hx.shop.utils.NetUtils;
import com.sl.hx.shop.utils.SPUtils;
import com.sl.hx.shop.utils.ToastUtil;
import com.trello.rxlifecycle2.android.ActivityEvent;
import com.umeng.analytics.MobclickAgent;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.util.Timer;
import java.util.TimerTask;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.Observable;

public class LogoActivity extends BaseActivity {

    private static String[] PERMISSIONS_STORAGE = {
            android.Manifest.permission.READ_EXTERNAL_STORAGE,
            android.Manifest.permission.WRITE_EXTERNAL_STORAGE};
    private static int REQUEST_CODE = 1;
    private boolean isFirstInstall;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_logo;
    }

    @Override
    protected BasePresenter createPresenter() {
        return null;
    }

    @Override
    protected void initView() {
        View decorView = getWindow().getDecorView();
        int uiOptions = View.SYSTEM_UI_FLAG_FULLSCREEN;
        decorView.setSystemUiVisibility(uiOptions);

        //判断当前版本
        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP) {
            if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(this, PERMISSIONS_STORAGE, REQUEST_CODE);//requesrCode
            } else {
                //已有权限
            }
        } else {
           // 小于6.0
        }

        isFirstInstall = SPUtils.getInstance().getBoolean(SPUKey.ISFIRSTINSTALL, true);
        if (isFirstInstall) {
            getToken();
            SPUtils.getInstance().put(SPUKey.ISFIRSTINSTALL, false);
        }
    }

    @Override
    protected void initData() {
        getSplash();
    }

    private void getToken() {
        Observable observable = ApiFactory.getInstance().getToken(AppConfig.CHANNEL);
        HttpUtil.getInstance().toSubscribe(observable, new ProgressSubscribe<TokenBean>(mContext) {
            @Override
            protected void _onNext(TokenBean tokenBean) {
                ShowToken(tokenBean);
            }

            @Override
            protected void _onError(String message) {
                ShowSplashFail();
            }
        }, false, this, ActivityEvent.DESTROY);
    }


    private void getSplash() {
        Observable observable = ApiFactory.getInstance().getOpen();
        HttpUtil.getInstance().toSubscribe(observable, new ProgressSubscribe<SplashBean>(mContext) {
            @Override
            protected void _onNext(SplashBean splashBean) {
                ShowSplash(splashBean);
            }

            @Override
            protected void _onError(String message) {
                ShowSplashFail();
            }
        }, false, this, ActivityEvent.DESTROY);
    }


    private void ShowSplash(final SplashBean splashBean) {
        new Handler().postDelayed(new Runnable() {
            public void run() {
                //state为0直接跳过广告页面,进入主页面
                if (splashBean.getState()==0) {
                    toActivity(MainActivity.class);
                    finish();
                } else {
                    //这里判断有无缓存,无缓存直接跳转主页面
                    if (TextUtils.isEmpty(SPUtils.getInstance().getString(SPUKey.SPLASHIMAGE))) {
                        //无缓存时将图片保存
                        Glide.with(mContext).asBitmap().load(splashBean.getLogo()).into(new SimpleTarget<Bitmap>() {
                            @Override
                            public void onResourceReady(Bitmap resource, Transition<? super Bitmap> transition) {
                                // 第一步:将Bitmap压缩至字节数组输出流ByteArrayOutputStream
                                ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
                                resource.compress(Bitmap.CompressFormat.PNG, 80, byteArrayOutputStream);
                                // 第二步:利用Base64将字节数组输出流中的数据转换成字符串String
                                byte[] byteArray = byteArrayOutputStream.toByteArray();
                                String image = new String(Base64.encodeToString(byteArray, Base64.DEFAULT));
                                // 第三步:将String保持至SharedPreferences
                                SPUtils.getInstance().put(SPUKey.SPLASHIMAGE, image);
                            }
                        });
                        toMainActivity();
                    } else {
                        //有缓存则将图片传至下页面
                        toSplashActivity(splashBean);
                    }
                }
            }
        }, 2000);
    }

    private void toSplashActivity(SplashBean splashBean) {
        Intent intent = new Intent(this, SplashActivity.class);
        intent.putExtra(SPUKey.SPLASHBEAN,splashBean);
        startActivity(intent);
        finish();
    }

    private void ShowToken(TokenBean tokenBean) {
        //将tokenID保存到本地
        //FileUtil.saveFile(tokenBean.getToken(),"hxg.txt");
        SPUtils.getInstance().put(SPUKey.TOKENID,tokenBean.getTokenid());
    }

    private void ShowSplashFail() {
        if (NetUtils.isConnected(this)) {
            ToastUtil.showShort(this,"请求失败");
        } else {
            ToastUtil.showShort(this, "当前网络未连接");
            toMainActivity();
        }
    }
    private void toMainActivity() {
        Intent intent = new Intent(this, MainActivity.class);
        startActivity(intent);
        finish();
    }

}
